package com.abcdefg.springmvcdemo.demo;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
@RequestMapping("/Session")
public class SessionDemo {
    //设置Session
    @RequestMapping("r1")
    public String r1(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session != null){
            session.setAttribute("name", "Jack");
        }
        return "设置Session成功";
    }
    //获取Session
    @RequestMapping("r2")
    public String r2(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session == null){
            return "session设置失败";
        }else{
            return "设置Session成功"+session.getAttribute("name");
        }
    }
    @RequestMapping("r3")
    public String r3(HttpSession session){
        if(session == null){
            return "session设置失败";
        }else{
            return "设置Session成功"+session.getAttribute("name");
        }
    }
    @RequestMapping("r4")
    public String r4(@SessionAttribute("name") String name){
        return name;
    }

}
